<script setup lang="ts">
import { ref, unref, watch, computed, onMounted, onBeforeUnmount } from "vue"
import { useConfigContextInject } from "ant-design-vue/es/config-provider/context"
import Button from "../button"
import Form from "../form"
import "./style.css"
import { useProvideCollapsisbleFormContext } from "./context"
import { ItemDefination } from "./types"

const configContext = useConfigContextInject()

// 控制表单是否折叠
const collapsed = ref<boolean>(true)

// 折叠时可以显示的元素数量
const visibleItemNumber = ref(9)

// 用于记录所有的元素
const items = ref<ItemDefination[]>([])

const itemSpans = computed(() => {
  return items.value.reduce((acc, curr) => {
    acc = acc + curr.span
    return acc
  }, 0)
})

useProvideCollapsisbleFormContext(items)

watch(
  [collapsed, visibleItemNumber, items],
  () => {
    if (!collapsed.value) {
      // 如果是展开状态，则显示所有元素
      for (let index in items.value) {
        items.value[index].visible = true
      }
      return
    }

    // 如果是折叠状态，则隐藏不需要显示的项目
    let spanCount = 0
    for (let index in items.value) {
      const item = items.value[index]
      spanCount += unref(item.span)
      if (spanCount <= visibleItemNumber.value) {
        items.value[index].visible = true
      } else {
        items.value[index].visible = false
      }
    }
  },
  { immediate: true, deep: true },
)

// 获取表单网格容器
const gridContainer = ref(null)

// 监听容器尺寸变化，并作出响应
let resizeObserver: ResizeObserver | null = null

onMounted(() => {
  if (gridContainer.value) {
    // 监听过滤器的列数变化
    resizeObserver = new ResizeObserver(() => {
      // 计算可显示的元素数量并赋值
      const columnNumber = window
        .getComputedStyle(gridContainer.value!)
        .gridTemplateColumns.split(" ").length
      // 一列时显示三行元素，否则显示两行
      visibleItemNumber.value = columnNumber === 1 ? 3 : columnNumber * 2 - 1
    })

    resizeObserver.observe(gridContainer.value)
  }
})

onBeforeUnmount(() => {
  if (resizeObserver) {
    // 关闭监听
    resizeObserver.disconnect()
  }
})
</script>

<template>
  <Form class="pc-collapsible-form">
    <div ref="gridContainer" class="pc-grid-container">
      <slot name="filters"></slot>
      <div class="pc-flex pc-gap-3">
        <slot name="actions"></slot>
        <Button
          v-if="itemSpans > visibleItemNumber"
          type="link"
          class="pc-text-[#]"
          @click="collapsed = !collapsed"
        >
          <div v-show="collapsed">
            {{
              configContext.locale?.value.locale === "zh-cn" ? "展开" : "Expand"
            }}
            <h-icon-down />
          </div>
          <div v-show="!collapsed">
            {{
              configContext.locale?.value.locale === "zh-cn"
                ? "收起"
                : "Collapse"
            }}
            <h-icon-up />
          </div>
        </Button>
      </div>
    </div>
  </Form>
</template>
